@echo off
setlocal enabledelayedexpansion

echo ========================================
echo 启动优化后的Sky外卖系统...
echo ========================================

REM === 可调参数（保留你原有设置风格）===
set "XMS=2g"
set "XMX=4g"
set "METASPACE=512m"
set "GC=G1"
set "APP_JAR=sky-server\target\sky-server.jar"

REM === 日志与转储文件 ===
set "BASE_DIR=%~dp0"
set "LOG_DIR=%BASE_DIR%logs"
set "HEAP_DUMP=%LOG_DIR%\heapdump.hprof"
if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"

REM === 选择 Java 可执行文件 ===
if defined JAVA_HOME (
  set "JAVA=%JAVA_HOME%\bin\java.exe"
) else (
  set "JAVA=java"
)

REM === 探测 Java 版本，决定使用哪套 GC 日志参数 ===
set "JV="
for /f "tokens=3 delims= " %%v in ('"%JAVA%" -version 2^>^&1 ^| findstr /i "version"') do set "JV=%%v"
REM JV 可能是 "1.8.0_XXX" 或 "17.0.9" 之类
set "JV_PREFIX=!JV:~0,3!"

if "!JV_PREFIX!"=="1.8" (
  REM JDK8 使用旧式 GC 日志参数（保留你原有写法）
  set "LOG_OPTS=-XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -Xloggc:%LOG_DIR%\gc.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=5 -XX:GCLogFileSize=20M"
) else (
  REM JDK11+/17+ 使用统一日志语法
  set "LOG_OPTS=-Xlog:gc*:file=%LOG_DIR%\gc.log:time,uptime,level,tags"
)

REM === 通用 JVM 选项（融合你原脚本与实战推荐）===
set "COMMON_OPTS=-server -Xms%XMS% -Xmx%XMX% -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=%METASPACE% -Xss512k -XX:+AlwaysPreTouch -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=%HEAP_DUMP% -XX:+OptimizeStringConcat"

REM === GC 选项（默认 G1；可切 ZGC）===
if /I "%GC%"=="G1" (
  set "GC_OPTS=-XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:InitiatingHeapOccupancyPercent=30 -XX:G1ReservePercent=15 -XX:+ParallelRefProcEnabled -XX:+UseStringDeduplication"
) else if /I "%GC%"=="ZGC" (
  REM 需要 JDK17+；追求更低停顿可启用
  set "GC_OPTS=-XX:+UseZGC"
) else (
  echo [WARN] 未知 GC=%GC%，回退到 G1
  set "GC_OPTS=-XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:InitiatingHeapOccupancyPercent=30 -XX:G1ReservePercent=15 -XX:+ParallelRefProcEnabled -XX:+UseStringDeduplication"
)

REM === 汇总并启动 ===
echo Using JAVA: %JAVA%
echo Java version detected: %JV%
echo Using GC: %GC%   Xms: %XMS%   Xmx: %XMX%
echo GC log: %LOG_DIR%\gc.log
echo HeapDump: %HEAP_DUMP%

"%JAVA%" %COMMON_OPTS% %GC_OPTS% %LOG_OPTS% -jar "%BASE_DIR%%APP_JAR%" %*

echo ========================================
echo 系统启动完成！
echo ========================================
pause
endlocal